import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CusTomBaseWidget extends StatefulWidget {
  const CusTomBaseWidget({required Key key, this.introduce: "认识基础组件"});

  final String introduce;

  @override
  _BaseWidgetState createState() => new _BaseWidgetState();
}

class _BaseWidgetState extends State<CusTomBaseWidget> {
  String preText = '默认密码';
  FocusNode focusNode1 = new FocusNode();
  FocusNode focusNode2 = new FocusNode();
  FocusScopeNode? focusScopeNode;

  ///用于文本输入框
  var controller = new TextEditingController(text: "默认密码");
  TextEditingController _pwdController = new TextEditingController();
  var textFormFieldKey = ValueKey("TextFormField");

  @override
  void initState() {
    super.initState();

    preText = '默认密码';
    controller.addListener(() {
      ///获取输入的内容
      String currentStr = controller.text;
      print(" controller 兼听 $currentStr");
    });
    // 设置默认值，并从第三个字符开始选中后面的字符
    controller.selection =
        TextSelection(baseOffset: 2, extentOffset: controller.text.length);

    ///控制 初始化的时候光标保持在文字最后
    controller = TextEditingController.fromValue(

      ///用来设置初始化时显示
      TextEditingValue(

        ///用来设置文本 controller.text = "0000"
        text: preText,

        ///设置光标的位置
        selection: TextSelection.fromPosition(

          ///用来设置文本的位置
          TextPosition(
              affinity: TextAffinity.downstream,

              /// 光标向后移动的长度
              offset: preText.length - 3),
        ),
      ),
    );
  }

  Color? getColor(Set<MaterialState> states) {
    if (states.contains(MaterialState.focused) &&
        !states.contains(MaterialState.pressed)) {
      //获取焦点时的颜色
      return Colors.blue;
    } else if (states.contains(MaterialState.pressed)) {
      //按下时的颜色
      return Colors.deepPurple;
    }
    //默认状态使用灰色
    return Colors.grey;
  }

  bool _switchSelected = true; //维护单选开关状态
  bool _checkboxSelected = true; //维护复选框状态

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
      body: Center(

          child: SingleChildScrollView(child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("普通文本"),
              TextButton(
                child: Text('自定义样式文本按钮'),
                style: ButtonStyle(
                  //定义文本的样式 这里设置的颜色是不起作用的
                  textStyle: MaterialStateProperty.all(
                      TextStyle(fontSize: 18, color: Colors.red)),
                  //设置按钮上字体与图标的颜色
                  //foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
                  //更优美的方式来设置
                  foregroundColor: MaterialStateProperty.resolveWith(
                        (states) {
                      if (states.contains(MaterialState.focused) &&
                          !states.contains(MaterialState.pressed)) {
                        //获取焦点时的颜色
                        return Colors.blue;
                      } else if (states.contains(MaterialState.pressed)) {
                        //按下时的颜色
                        return Colors.deepPurple;
                      }
                      //默认状态使用灰色
                      return Colors.grey;
                    },
                  ),
                  //背景颜色
                  backgroundColor: MaterialStateProperty.resolveWith((states) {
                    //设置按下时的背景颜色
                    if (states.contains(MaterialState.pressed)) {
                      return Colors.blue[200];
                    }
                    //默认不使用背景颜色
                    return null;
                  }),
                  //设置水波纹颜色
                  overlayColor: MaterialStateProperty.all(Colors.yellow),
                  //设置阴影  不适用于这里的TextButton
                  elevation: MaterialStateProperty.all(0),
                  //设置按钮内边距
                  padding: MaterialStateProperty.all(EdgeInsets.all(10)),
                  //设置按钮的大小
                  minimumSize: MaterialStateProperty.all(Size(200, 100)),
                  //设置边框
                  side: MaterialStateProperty.all(
                      BorderSide(color: Colors.grey, width: 1)),
                  //外边框装饰 会覆盖 side 配置的样式
                  shape: MaterialStateProperty.all(StadiumBorder()),
                ),
                onPressed: () {},
              ),
              OutlinedButton.icon(
                onPressed: () => Navigator.pop(context, "我是返回值"),
                icon: Image.network(
                  "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
                  width: 100.0,
                  color: Colors.blue,
                  colorBlendMode: BlendMode.difference,
                ),
                label: Text("返回"),
              ),
              OutlinedButton(
                onPressed: () => Navigator.pop(context, "我是返回值"),
                child: Text("返回"),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.resolveWith(
                        getColor)),
              ),
              IconButton(
                icon: Icon(
                  Icons.thumb_up,
                  color: Color(0xFFA0951D),
                ),
                onPressed: () {},
              ),
              Switch(
                value: _switchSelected, //当前状态
                onChanged: (value) {
                  //重新构建页面
                  setState(() {
                    _switchSelected = value;
                  });
                },
              ),
              Checkbox(
                value: _checkboxSelected,
                activeColor: Colors.red, //选中时的颜色
                onChanged: (value) {
                  setState(() {
                    if (value != null) {
                      _checkboxSelected = value;
                    }
                  });
                },
              ),
              TextFormField(
                // key: textFormFieldKey,
                  autofocus: true,
                  controller: controller,
                  focusNode: focusNode1,
                  decoration: InputDecoration(
                    // labelText: "用户名",
                      hintText: "用户名或邮箱",
                      prefixIcon: Icon(Icons.person)),
                  validator: (v) {
                    return v!.trim().length > 0 ? null : "用户名不能为空";
                  }),
              TextFormField(
                // key: textFormFieldKey,
                  controller: _pwdController,
                  focusNode: focusNode2,
                  decoration: InputDecoration(
                    // labelText: "密码",
                      hintText: "您的登录密码",
                      prefixIcon: Icon(Icons.lock)),
                  //校验密码
                  validator: (v) {
                    return v!.trim().length > 5 ? null : "密码不能少于6位";
                  },
                  obscureText: true,
                  onChanged: _passwordOnChanged),
              // 登录按钮
              Padding(
                padding: const EdgeInsets.only(top: 28.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: RaisedButton(
                        padding: EdgeInsets.all(15.0),
                        child: Text("登录"),
                        color: Theme
                            .of(context)
                            .primaryColor,
                        textColor: Colors.white,
                        onPressed: () {
                          // if ((_formKey.currentState as FormState).validate()) {
                          //   //验证通过提交数据
                          // }
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                                return FormTestRoute();
                              }));
                          //在这里不能通过此方式获取FormState，context不对
                          //print(Form.of(context));

                          // 通过_formKey.currentState 获取FormState后，
                          // 调用validate()方法校验用户名密码是否合法，校验
                          // 通过后再提交数据。
                        },
                      ),
                    ),
                  ],
                ),
              ),
              ElevatedButton(
                child: Text("移动焦点"),
                onPressed: () {
                  //将焦点从第一个TextField移到第二个TextField
                  // 这是一种写法 FocusScope.of(context).requestFocus(focusNode2);
                  // 这是第二种写法
                  if (null == focusScopeNode) {
                    focusScopeNode = FocusScope.of(context);
                  }
                  focusScopeNode?.requestFocus(focusNode2);
                },
              ),
              ElevatedButton(
                child: Text("隐藏键盘"),
                onPressed: () {
                  // 当所有编辑框都失去焦点时键盘就会收起
                  focusNode1.unfocus();
                  focusNode2.unfocus();
                },
              ),
              TextField(
                //自定义输入框
                decoration: InputDecoration(
                  labelText: "请输入用户名",
                  prefixIcon: Icon(Icons.person),
                  // 未获得焦点下划线设为灰色
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey),
                  ),
                  //获得焦点下划线设为蓝色
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.blue),
                  ),
                ),
              ),
              CustomInputWidget(),
              //文本边框，背景,带删除按钮
              CustomInputDelWidget(),


            ],
          ),
          )),
    );
  }

  void _passwordOnChanged(String value) {
    print("密码输入值改变了onChange: $value");
  }

  @override
  void didUpdateWidget(covariant CusTomBaseWidget oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print("didUpdateWidget");
  }

  @override
  void deactivate() {
    super.deactivate();
    print("deactive");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("reassemble");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }
}
/*自定义一个输入框样式 带背景的那种,删除*/
class CustomInputDelWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return CustomInputDelWidgetState();
  }

}

class CustomInputDelWidgetState extends State<CustomInputDelWidget> {

  //输入焦点
  FocusNode _inputFocusNode = FocusNode();

  //TextField控制器
  final TextEditingController _inputController = TextEditingController();

  void initInputListener(FocusNode focusNode){
    focusNode.addListener(() {
      if(focusNode.hasFocus){
        print("tgwinput---输入框聚焦");
        setState(() {

        });
      }else{
        print("tgwinput---输入框失焦");
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //输入框焦点监听
    _inputFocusNode.unfocus();
    initInputListener(_inputFocusNode);
    //初始化文本
    _inputController.text = "123";

  }


  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: 40,
          width: 264,
          //圆弧背景
          decoration: (_inputFocusNode.hasFocus) ? BoxDecoration( //当hover和有值时显示常态
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(20)),
              border: (true) ? Border.all( //当有焦点和hover时显示蓝色边框//
                color: Color(0XFF3B83FC), //边框颜色//
                width: 1.0, //线宽度//
              ) : Border.all(
                color: Color(0XFFD9D9D9), //边框颜色//
                width: 1.0, //线宽度//
              )
          )
              : BoxDecoration( //无内容无hover显示
            color: Color(0XFFF4F5F6),
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),),
        Container(
          margin: EdgeInsets.only(left: 16, top: 3),
          width: 202,
          height: 40,
          child: TextField(
            focusNode: _inputFocusNode,
            obscureText: true,
            controller:  _inputController,//TextEditingController 文本控制器
            cursorColor: Color(0xFF000000),
            cursorWidth: 1,
            maxLines: 1,
            maxLength: 50,
            enableInteractiveSelection: false,
            textAlignVertical: TextAlignVertical.center,
            //限制输入汉字和空格
            inputFormatters: [
              FilteringTextInputFormatter.deny(RegExp('[\u4e00-\u9fa5]|[ ]'))
            ],
            decoration: InputDecoration(
              //取消计数器
                counterText: '',
                border: InputBorder.none,
                hintText: '请输入密码',
                hintStyle: TextStyle(
                    fontSize: 14, color: Color(0xffbfbfbf), height: 2)
            ),
            onChanged: (value) {

            },
          ),
        ),
        (_inputFocusNode.hasFocus) ?
        Container(
            height: 16,
            width: 16,
            margin: EdgeInsets.only(left: 213, top: 12),
            child: InkWell(
              onTapDown: (e) {
                _inputFocusNode.unfocus();
              },
              onHover: (e) {
                setState(() {

                });
              },
              onTap: () {
                setState(() {
                  _inputController.clear();
                  _inputController.text = '';

                  // FocusScope.of(context).requestFocus(
                  //     _inputFocusNode); //按下清除键时焦点在密码框

                });
              },
              child: Image.asset('images/Login/LoginEmpty.png'),
            ),
        ) : Container(),
      ],
    );
  }


}


/*自定义一个输入框样式*/
class CustomInputWidget extends StatelessWidget {
  const CustomInputWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Scaffold? scaffold = context.findAncestorWidgetOfExactType<Scaffold>();
    // 直接返回 AppBar的title， 此处实际上是Text("Context测试")
    // var partText =(scaffold?.appBar as AppBar).title;
    return Theme(
        data: Theme.of(context).copyWith(
            hintColor: Colors.grey[200], //定义下划线颜色
            inputDecorationTheme: InputDecorationTheme(
                labelStyle: TextStyle(color: Colors.grey), //定义label字体样式
                hintStyle:
                TextStyle(color: Colors.grey, fontSize: 14.0) //定义提示文本样式
            )),
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                  labelText: "用户名",
                  hintText: "用户名或邮箱",
                  prefixIcon: Icon(Icons.person)),
            ),
            TextField(
              decoration: InputDecoration(
                  prefixIcon: Icon(Icons.lock),
                  labelText: "密码",
                  hintText: "您的登录密码",
                  hintStyle:
                  TextStyle(color: Color(0xFFEC1010), fontSize: 13.0)),
              obscureText: true,
            )
          ],
        ));
  }
}


class FormTestRoute extends StatefulWidget {
  @override
  _FormTestRouteState createState() => new _FormTestRouteState();
}

class _FormTestRouteState extends State<FormTestRoute> {
  TextEditingController _unameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Form Test"),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
        child: Form(
          key: _formKey, //设置globalKey，用于后面获取FormState
          autovalidateMode: AutovalidateMode.always, //开启自动校验
          child: Column(
            children: <Widget>[
              TextFormField(
                  autofocus: true,
                  controller: _unameController,
                  decoration: InputDecoration(
                      labelText: "用户名",
                      hintText: "用户名或邮箱",
                      icon: Icon(Icons.person)),
                  // 校验用户名
                  validator: (v) {
                    return v!.trim().length > 0 ? null : "用户名不能为空";
                  }),
              TextFormField(
                  controller: _pwdController,
                  decoration: InputDecoration(
                      labelText: "密码",
                      hintText: "您的登录密码",
                      icon: Icon(Icons.lock)),
                  obscureText: true,
                  //校验密码
                  validator: (v) {
                    return v!.trim().length > 5 ? null : "密码不能少于6位";
                  }),
              // 登录按钮
              Padding(
                padding: const EdgeInsets.only(top: 28.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: RaisedButton(
                        padding: EdgeInsets.all(15.0),
                        child: Text("登录"),
                        color: Theme
                            .of(context)
                            .primaryColor,
                        textColor: Colors.white,
                        onPressed: () {
                          //在这里不能通过此方式获取FormState，context不对
                          //print(Form.of(context));

                          // 通过_formKey.currentState 获取FormState后，
                          // 调用validate()方法校验用户名密码是否合法，校验
                          // 通过后再提交数据。
                          if ((_formKey.currentState as FormState).validate()) {
                            //验证通过提交数据
                            Navigator.push(context,
                                MaterialPageRoute(builder: (context) {
                                  return ProgressRoute();
                                }));
                          }
                        },
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class ProgressRoute extends StatefulWidget {
  @override
  _ProgressRouteState createState() => _ProgressRouteState();
}

class _ProgressRouteState extends State<ProgressRoute>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    //动画执行时间3秒
    _animationController =
    new AnimationController(vsync: this, duration: Duration(seconds: 3));
    _animationController.forward();
    _animationController.addListener(() =>
        setState(() =>
        {
          print("进度条长度：${_animationController.value}")
        }));
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(16),
            child: LinearProgressIndicator(
              backgroundColor: Colors.grey[200],
              valueColor: ColorTween(begin: Colors.grey, end: Colors.blue)
                  .animate(_animationController), // 从灰色变成蓝色
              value: _animationController.value,
            ),
          ),
        ],
      ),
    );
  }
}
